<template>
  <div class="banner-management">
    <h2 class="page-title">轮播图管理</h2>
    
    <!-- 操作按钮 -->
    <div class="actions">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加轮播图</el-button>
    </div>
    
    <!-- 轮播图列表 -->
    <el-table
      :data="bannerList"
      border
      style="width: 100%"
      v-loading="loading">
      <el-table-column
        prop="id"
        label="ID"
        width="80">
      </el-table-column>
      <el-table-column
        prop="title"
        label="标题"
        width="150">
      </el-table-column>
      <el-table-column
        prop="image"
        label="图片"
        width="200">
        <template slot-scope="scope">
          <img :src="scope.row.image" alt="轮播图" class="banner-image">
        </template>
      </el-table-column>
      <el-table-column
        prop="url"
        label="链接URL"
        width="200">
      </el-table-column>
      <el-table-column
        prop="sort"
        label="排序"
        width="80">
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ scope.row.status === 1 ? '已启用' : '已禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="180">
      </el-table-column>
      <el-table-column
        label="操作"
        width="250">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            :type="scope.row.status === 1 ? 'warning' : 'success'"
            @click="handleToggleStatus(scope.row)">
            {{ scope.row.status === 1 ? '禁用' : '启用' }}
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    
    <!-- 添加/编辑轮播图对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '添加轮播图' : '编辑轮播图'"
      :visible.sync="dialogVisible"
      width="50%">
      <el-form :model="bannerForm" :rules="rules" ref="bannerForm" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="bannerForm.title" placeholder="请输入轮播图标题"></el-input>
        </el-form-item>
        <el-form-item label="图片URL" prop="image">
          <el-upload
            class="image-uploader"
            :action="`${$baseURL}/api/upload/common`"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload">
            <img v-if="bannerForm.image" :src="bannerForm.image" class="uploaded-image">
            <i v-else class="el-icon-plus image-uploader-icon"></i>
          </el-upload>
          <div class="image-tips">
            <p>点击上方区域上传图片，或直接输入图片URL</p>
            <el-input v-model="bannerForm.image" placeholder="请输入图片URL"></el-input>
          </div>
          <div class="image-preview" v-if="bannerForm.image">
            <img :src="bannerForm.image" alt="预览图" class="preview-image">
          </div>
        </el-form-item>
        <el-form-item label="链接URL" prop="url">
          <el-input v-model="bannerForm.url" placeholder="请输入点击轮播图跳转的链接"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="bannerForm.description" type="textarea" placeholder="请输入轮播图描述"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="bannerForm.sort" :min="0" :max="999"></el-input-number>
          <span class="tip">数值越小，排序越靠前</span>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="bannerForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getBannerList,
  addBanner,
  updateBanner,
  deleteBanner,
  updateBannerStatus
} from '@/api/banner'

export default {
  name: 'BannerManagement',
  data() {
    return {
      // 轮播图列表
      bannerList: [],
      // 加载状态
      loading: false,
      // 分页参数
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 对话框参数
      dialogVisible: false,
      dialogType: 'add', // add: 添加, edit: 编辑
      // 表单数据
      bannerForm: {
        id: null,
        title: '',
        image: '',
        url: '',
        description: '',
        sort: 0,
        status: 1
      },
      // 表单验证规则
      rules: {
        title: [
          { required: true, message: '请输入轮播图标题', trigger: 'blur' },
          { max: 50, message: '标题长度不能超过50个字符', trigger: 'blur' }
        ],
        image: [
          { required: true, message: '请输入图片URL', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入排序值', trigger: 'blur' }
        ]
      },
   
    }
  },
  computed: {
    // 上传图片需要的headers
    uploadHeaders() {
      return {
        Authorization: `Bearer ${this.$store.getters.token}`
      }
    }
  },
  created() {
    this.fetchBannerList()
  },
  methods: {
    // 获取轮播图列表
    fetchBannerList() {
      this.loading = true
      getBannerList(this.currentPage, this.pageSize)
        .then(response => {
          if (response.code == 200) {
            this.bannerList = response.data
            this.total = response.total || 0
          } else {
            this.$message.error(response.message || '获取轮播图列表失败')
          }
        })
        .catch(error => {
          console.error('获取轮播图列表失败', error)
          this.$message.error('获取轮播图列表失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    // 添加轮播图
    handleAdd() {
      this.dialogType = 'add'
      this.resetForm()
      this.dialogVisible = true
    },
    
    // 编辑轮播图
    handleEdit(row) {
      this.dialogType = 'edit'
      this.bannerForm = { ...row }
      this.dialogVisible = true
    },
    
    // 切换轮播图状态
    handleToggleStatus(row) {
      const newStatus = row.status === 1 ? 0 : 1
      const statusText = newStatus === 1 ? '启用' : '禁用'
      
      this.$confirm(`确认${statusText}该轮播图吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateBannerStatus(row.id, newStatus)
          .then(response => {
            if (response.code == 200) {
              this.$message.success(`${statusText}成功`)
              // 更新本地数据
              row.status = newStatus
            } else {
                this.$message.error(response.message || `${statusText}失败`)
            }
          })
          .catch(error => {
            console.error(`${statusText}失败`, error)
            this.$message.error(`${statusText}失败`)
          })
      }).catch(() => {
        // 取消操作
      })
    },
    
    // 删除轮播图
    handleDelete(row) {
      this.$confirm('确认删除该轮播图吗? 此操作不可恢复!', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        deleteBanner(row.id)
          .then(response => {
            if (response.code == 200) {
              this.$message.success('删除成功')
              this.fetchBannerList()
            } else {
              this.$message.error(response.message || '删除失败')
            }
          })
          .catch(error => {
            console.error('删除失败', error)
            this.$message.error('删除失败')
          })
      }).catch(() => {
        // 取消操作
      })
    },
    
    // 提交表单
    submitForm() {
      this.$refs.bannerForm.validate(valid => {
        if (valid) {
          if (this.dialogType === 'add') {
            // 添加轮播图
            addBanner(this.bannerForm)
              .then(response => {
                if (response.code == 200) {
                  this.$message.success('添加成功')
                  this.dialogVisible = false
                  this.fetchBannerList()
                } else {
                  this.$message.error(response.message || '添加失败')
                }
              })
              .catch(error => {
                console.error('添加失败', error)
                this.$message.error('添加失败')
              })
          } else {
            // 编辑轮播图
            updateBanner(this.bannerForm.id, this.bannerForm)
              .then(response => {
                if (response.code == 200) {
                  this.$message.success('更新成功')
                  this.dialogVisible = false
                  this.fetchBannerList()
                } else {
                  this.$message.error(response.message || '更新失败')
                }
              })
              .catch(error => {
                console.error('更新失败', error)
                this.$message.error('更新失败')
              })
          }
        } else {
          return false
        }
      })
    },
    
    // 重置表单
    resetForm() {
      this.bannerForm = {
        id: null,
        title: '',
        image: '',
        url: '',
        description: '',
        sort: 0,
        status: 1
      }
      if (this.$refs.bannerForm) {
        this.$refs.bannerForm.resetFields()
      }
    },
    
    // 分页大小变化
    handleSizeChange(size) {
      this.pageSize = size
      this.fetchBannerList()
    },
    
    // 当前页变化
    handleCurrentChange(page) {
      this.currentPage = page
      this.fetchBannerList()
    },

    // 处理图片上传成功后的逻辑
    handleImageSuccess(res) {
      if (res.code == 200) {
        this.bannerForm.image = res.data.fileUrl
        this.$message.success('图片上传成功')
      } else {
        this.$message.error(res.message || '图片上传失败')
      }
    },

    // 处理图片上传前的逻辑
    beforeImageUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传的文件必须是图片!')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过2MB!')
      }
      return isImage && isLt2M
    }
  }
}
</script>

<style scoped>
.banner-management {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
}

.actions {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-start;
}

.banner-image {
  width: 100px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.image-preview {
  margin-top: 10px;
}

.preview-image {
  max-width: 300px;
  max-height: 150px;
  border-radius: 4px;
}

.tip {
  margin-left: 10px;
  color: #909399;
  font-size: 12px;
}

.image-uploader {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  overflow: hidden;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  line-height: 100px;
  text-align: center;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-tips {
  margin-top: 10px;
}
</style> 